package com.erf.handler.server;

import com.erf.message.LoginRequest;
import com.erf.message.LoginRequestResponse;
import com.erf.session.Session;
import com.erf.tmpdb.DBMap;
import io.netty.channel.*;
import io.netty.util.AttributeKey;
import lombok.extern.slf4j.Slf4j;

/**
 * @author zhangzy
 * @date 2022/7/5
 */
@ChannelHandler.Sharable
@Slf4j
public class LoginRequestHandler extends SimpleChannelInboundHandler<LoginRequest> {
    /**
     * 鉴权key
     */
    public static final AttributeKey<String> KEY = AttributeKey.valueOf("user");

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, LoginRequest loginRequest) throws Exception {
        log.info("[server_receive]" + loginRequest);
        Channel channel = ctx.channel();
        String channelId = channel.id().asShortText();
        LoginRequestResponse loginRequestResponse = new LoginRequestResponse();
        loginRequestResponse.setSequence(loginRequest.getSequence());
        String name = loginRequest.getName();
        String password = loginRequest.getPassword();
        String s = DBMap.loginMap.get(name);
        if (s != null && s.equals(password)) {
            //设置登录权限
            channel.attr(KEY).set(name);
            //记录session
            Session.put(name, channel);
            loginRequestResponse.setCode(0);
            loginRequestResponse.setDescription("登录成功");
            ctx.writeAndFlush(loginRequestResponse);
        } else {
            loginRequestResponse.setCode(-1);
            loginRequestResponse.setDescription("登录失败");
            ChannelFuture response = ctx.channel().writeAndFlush(loginRequestResponse);
            response.addListener(future -> {
                        log.info("client:" + channelId + " 登录失败，连接正在断开...");
                        ctx.channel().close();
                    }
            );
        }
    }
}
